"use strict";

const semver = require("semver");
const colors = require("colors/safe");
const log = require("@luojia-cli-dev/log");
const { isObject } = require("@luojia-cli-dev/utils");

const LOWEST_NODE_VERSION = "12.0.0";

class Command {
  constructor(argv) {
    console.log("Command constructor", argv);
    this._argv = argv; // 接到参数
    if (!argv) {
      throw new Error("参数不能为空！");
    }
    if (!Array.isArray(argv)) {
      throw new Error("参数必须为数组！");
    }
    if (argv.length < 1) {
      throw new Error("参数列表为空!");
    }
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgs());
      chain.catch((err) => {
        log.error(err.message);
      });
    });
  }

  init() {
    throw new Error("init必须实现");
  }
  exec() {
    throw new Error("exec必须实现");
  }
  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
    console.log(this._cmd, this._argv);
  }
  /**
   * @Author: luo1o1o1o
   * @Date: 2021-11-08 18:44
   * @desc: 检查node版本
   */
  checkNodeVersion() {
    // 第一步，获取当前版本号
    const currentVersion = process.version;
    // 第二部，对比最低版本号
    const lowestVersion = LOWEST_NODE_VERSION; // 配置文件最低版本
    if (!semver.gte(currentVersion, lowestVersion)) {
      // 如果低于最低版本, 报错
      throw new Error(
        colors.red(`imooc-cli 需要安装 v${lowestVersion} 以上版本的 Node.js`)
      );
    }
  }
}

module.exports = Command;
